import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/* 工具类DBUtils , 该类中提供静态获取Connection连接的方法 */

public class DBUtils {

    //1. 定义字符串常量, 用于接收连接所需要的信息
    public static String DRIVERNAME;
    public static String URL;
    public static String USER;
    public static String PASSWORD;
    private static Properties props = new Properties();

    //2. 静态代码块, 随着类的加载而加载
    static{
        InputStream is = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            //注册驱动
            props.load(is);
            DRIVERNAME = props.getProperty("driverClassName");
            URL = props.getProperty("url");
            USER = props.getProperty("username");
            PASSWORD = props.getProperty("password");
            Class.forName(DRIVERNAME);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //3. 获取连接的静态方法
    public static Connection getConnection(){
        try{
            // 获取连接对象
            Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);

            // 返回连接对象
            return connection;
        }    catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 4. 关闭资源的静态方法（1）
    public static void close(Connection con, Statement st){
        if(con != null && st != null){
            try {
                st.close();
                con.close();
            }  catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 4. 关闭资源的静态方法（2）
    public static void close(Connection con, Statement st, ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        close(con,st);
    }
}